package me.xiaoyan.android.tuition.activity;

import java.util.HashMap;
import java.util.Map;

import me.xiaoyan.android.net.AsyncImageLoader;
import me.xiaoyan.android.net.AsyncImageLoader.ImageCallback;
import me.xiaoyan.android.tuition.R;
import me.xiaoyan.android.tuition.utils.AppManager;
import me.xiaoyan.android.tuition.utils.CodeUtil;
import me.xiaoyan.android.tuition.utils.SESHttp;
import me.xiaoyan.android.tuition.utils.TuitionException;
import me.xiaoyan.android.widget.BaseUtil;
import me.xiaoyan.android.widget.DataBackListener;
import me.xiaoyan.android.widget.YLog;
import me.xiaoyan.json.JSONArray;
import me.xiaoyan.json.JSONObject;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

public class Schools extends Common {
	private static final String TAG = "Activity.Schools";

	private LinearLayout llSchoolScholler;
	private AsyncImageLoader imgLoader = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_home);
		clickGoto(R.id.btn_home_login, Login.class);
		llSchoolScholler = (LinearLayout) findViewById(R.id.ll_home_school_list);
		imgLoader = new AsyncImageLoader();
		initUI();
		initAppData();
		autoLogin();
	}

	/**
	 * 初始化数据
	 */
	private void initAppData() {

		final Map<String, Object> param = new HashMap<String, Object>();

		param.put("pageIndex", 1);
		param.put("pageSize", 20);
		final ProgressDialog pd = getProgress(
				getString(R.string.loading_net_data), false);

		SESHttp.sendRequest(GET_SCHOOLS, param, new DataBackListener() {
			@Override
			public void success(String source) {
				pd.dismiss();
				System.out.println("DataBackListener" + source);

				try {
					JSONArray json = checkSESData(source);
					for (int i = 0; i < json.length(); i++) {
						JSONObject school = json.getJSONObject(i);
						// 获取数据并添加到界面
						addSchool(school.optString("url"),
								school.optString("schoolName"),
								school.optString("schoolId"));
					}
				} catch (Exception e) {
					showToast(
							getString(R.string.load_data_failed)
									+ e.getMessage(), Toast.LENGTH_SHORT);
				}
			}

			@Override
			public void failed(TuitionException e) {
				if (e.getErrorCode() == CodeUtil.ERROR_TIMEOUT
						|| e.getErrorCode() == CodeUtil.ERROR_NETWORK) {
					showReLoadData(GET_SCHOOLS, param, this);
				}
				pd.dismiss();
				e.printStackTrace();
			}
		});
	}

	@Override
	protected void onResume() {
		checkLogin();
		super.onResume();
	}

	private void initUI() {
		findViewById(R.id.btn_home_logout).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						AppManager.getInstance().delAppDatas(CUSTOMER_ID);
						showToast(getString(R.string.logout_success),
								Toast.LENGTH_SHORT);
						findViewById(R.id.btn_home_logout).setVisibility(
								View.GONE);
						findViewById(R.id.btn_home_login).setVisibility(
								View.VISIBLE);
					}
				});
	}

	private void checkLogin() {

		if (AppManager.getInstance().hasAppDatas(CUSTOMER_ID)) {
			findViewById(R.id.btn_home_logout).setVisibility(View.VISIBLE);
			findViewById(R.id.btn_home_login).setVisibility(View.GONE);
		} else {
			findViewById(R.id.btn_home_logout).setVisibility(View.GONE);
			findViewById(R.id.btn_home_login).setVisibility(View.VISIBLE);
		}
	}

	private void addSchool(String img, String name, String schoolId) {
		LayoutInflater layout = LayoutInflater.from(this);
		LinearLayout view = (LinearLayout) layout.inflate(
				R.layout.single_ui_home_item, null);
		final int imageWidth = BaseUtil.dip2px(this,
				BaseUtil.getPhoneWidthDip(this) - 30);

		final ImageView image = (ImageView) view
				.findViewById(R.id.img_home_school_img);

		imgLoader.getBitMap(img, new ImageCallback() {
			@Override
			public void imageLoaded(Bitmap drawable) {
				image.setImageBitmap(BaseUtil.zoomImage(imageWidth, drawable));
			}
		});
		Intent i = new Intent(this, StudentNoInput.class);
		i.putExtra("schoolId", schoolId);
		clickGoto(view, i);
		llSchoolScholler.addView(view);
	}

	@Override
	public void onBackPressed() {
		super.appexit();
	}

	// 自动登陆
	private void autoLogin() {
		SharedPreferences settings = getSharedPreferences(APP_DATA_KEY,
				Context.MODE_PRIVATE);
		Map<String, Object> param = new HashMap<String, Object>();
		String phone = settings.getString(APP_DATA_PHONE, "");
		String pass = settings.getString(APP_DATA_PASS, "");
		if (BaseUtil.stringIsEmpty(phone) || BaseUtil.stringIsEmpty(pass)) {
			return;
		}
		param.put("loginAccount", phone);
		param.put("pwd", pass);
		param.put("verifyCode", "1234");
		SESHttp.sendRequest(USER_LOGIN, param, new DataBackListener() {

			@Override
			public void success(String source) {
				System.out.println("DataBackListener" + source);
				try {
					JSONArray json = checkSESData(source);
					if (json.length() > 0) {
						String customerid = json.getJSONObject(0).optString(
								"customerId");
						AppManager.getInstance().saveAppDatas(CUSTOMER_ID,
								customerid);
						checkLogin();
					}
				} catch (Exception e) {
					YLog.e(TAG, e);
				}
			}

			@Override
			public void failed(TuitionException e) {
				YLog.e(TAG, e);
			}
		});
	}
}
